package com.copa.l77;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author copa
 * @createDate 2022-05-16 17:27
 * @function 回溯法 这种更简洁
 */
public class Test2 {

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        // 首先从这里定义的函数来看，begin定义了遍历过程
        backTracking(n, k, result, new ArrayList<Integer>(), 1);
        return result;
    }

    private void backTracking(int n, int k, List<List<Integer>> result, ArrayList<Integer> tempList, int begin) {
        if (k == tempList.size()) {
            result.add(new ArrayList<>(tempList));
            return;
        }
        for (int i = begin; i <= n; i++) {
            tempList.add(i);
            // 这里采用的是剪枝的方式，就不用像test1那样特定加判断了
            backTracking(n, k, result, tempList, i + 1);
            tempList.remove(tempList.size() - 1);
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> result = new Test2().combine(4, 2);
        for (List<Integer> list : result) {
            System.out.println(Arrays.toString(list.toArray()));
        }
    }
}
